package com.wit.witmg.api;

import com.wit.witmg.service.OSSService;
import com.wit.witmg.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.util.List;

/**
 * @author wupx
 * @date 2020/07/09
 */
@Controller
@RequestMapping("oss/")
@Api(tags = "阿里云OSS")
public class OSSController {

    @Autowired
    private OSSService ossService;


    @ApiOperation( "文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", dataType = "MultipartFile"),
            @ApiImplicitParam(name = "storagePath", value = "文件夹", dataType = "String"),
            @ApiImplicitParam(name = "fileName", value = "文件名，需要带上后缀", dataType = "String")})
    @PostMapping(value = "uploadFiles")
    public Object uploadFiles(@RequestParam("file") MultipartFile file,
                              @RequestParam("storagePath") String storagePath,
                              @RequestParam("fileName") String fileName) {
         ossService.uploadFile(file, fileName,storagePath);
         return JsonResult.success();
    }


    @ApiOperation( "下载文件")
    @RequestMapping(value = "down")
    public void exportFile(OutputStream os, @RequestParam("storagePath") String storagePath,@RequestParam("fileName") String fileName) {
        ossService.exportFile(os, storagePath+"/"+fileName);
    }

    @ApiOperation( "获取 url")
    @RequestMapping(value = "getUrl")
    public String getSingeNatureUrl(@RequestParam("storagePath") String storagePath,@RequestParam("fileName") String fileName) {
        return "redirect:"+ ossService.getSingeNatureUrl(storagePath+"/"+fileName, 10000000);
    }

    @ApiOperation( "删除文件")
    @PostMapping(value = "deleteFile")
    public void deleteFile(@RequestParam("fileName") String fileName) {
        ossService.deleteFile(fileName);
    }


    @ApiOperation( "查看文件列表")
    @PostMapping(value = "listObjects")
    public List<String> listObjects() {
        return ossService.listObjects();
    }

    @ApiOperation( "判断文件是否存在")
    @PostMapping(value = "doesObjectExist")
    public boolean doesObjectExist(@RequestParam("fileName") String fileName) {
        return ossService.doesObjectExist(fileName);
    }



    @ApiOperation( "设置文件访问权限")
    @PostMapping(value = "setObjectAcl")
    public void setObjectAcl(@RequestParam("fileName") String fileName) {
        ossService.setObjectAcl(fileName);
    }
}
